﻿using Mapster;
using Orleans.Providers;
using Orleans.Streams;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace orleans_demo.Services
{
    //list
    [StorageProvider(ProviderName = "SnapshotStore")]
    public class UserIndexGrain : Grain<List<UserInfo>>, IUserIndexGrain
    {
        public Task AddUser(UserInfo user)
        {
           var data = State.FirstOrDefault(x => x.Id == user.Id);
            if (data == null || string.IsNullOrEmpty(data.Id))
                State.Add(user);
            return WriteStateAsync();
        }

        public Task RemoveUser(string userId)
        {
            var user = State.FirstOrDefault(x => x.Id == userId);
            if(user != null && !string.IsNullOrEmpty(user.Id))
            {
                State.Remove(user);
                return WriteStateAsync();
            }
            return Task.CompletedTask;
        }

        public Task<List<UserInfo>> GetAllUser() => Task.FromResult(State);
    }

    // UserQueryGrain.cs 使用流查询
    [StorageProvider(ProviderName = "SnapshotStore")]
    public class UserQueryGrain : Grain<List<UserInfo>>, IUserQueryGrain
    {
        private IAsyncStream<UserEvent> _stream;
        private StreamSubscriptionHandle<UserEvent> _subscription;

        public override async Task OnActivateAsync(CancellationToken cancellationToken)
        {
            var streamProvider = this.GetStreamProvider("UserStream");
            _stream = streamProvider.GetStream<UserEvent>("0", "ALL_USERS");
            _subscription = await _stream.SubscribeAsync(OnNextEvent);

            // 初始化缓存（首次加载全量数据）
            if (State == null || State.Count == 0)
                await RebuildCacheAsync();
        }

        private async Task OnNextEvent(UserEvent evt, StreamSequenceToken token)
        {
            // 处理事件更新缓存
            switch (evt)
            {
                case UserCreatedEvent created:
                    State.Add(created.Adapt<UserInfo>());
                    break;
                case UserDeletedEvent _:
                    var delData = State.FirstOrDefault(x => x.Id == evt.Id);
                    if (delData != null && !string.IsNullOrEmpty(delData.Id))
                    {
                        State.Remove(delData);
                    }
                    break;
            }
            await WriteStateAsync();
        }

        public async Task<(List<UserInfo> Users, bool HasMore)> GetUsers(int pageNumber, int pageSize)
        {
            var allUsers = State.OrderBy(u => u.CreatedAt).ToList();
            var paged = allUsers
                .Skip((pageNumber - 1) * pageSize)
                .Take(pageSize)
                .ToList() ?? new List<UserInfo>();
            return (paged, (pageNumber * pageSize) < allUsers.Count);
        }

        private async Task RebuildCacheAsync()
        {
            // 从事件存储重建缓存（略）
        }

        public async Task SubscribeUpdates(IAsyncObserver<UserEvent> observer)
        {
            await Task.CompletedTask;
        }
    }
}
